# -*- coding: utf-8 -*-
from flask import Flask, jsonify, request
import json
import base64
import yaml
import copy
import time
import numpy as np
import cv2
from feature_extract import FoodParser
import utils

g_cfg_file = r'../config/config.yaml'
with open(g_cfg_file, 'r') as fopen:
    yaml_config = yaml.load(fopen, Loader=yaml.SafeLoader)

g_config = copy.deepcopy(yaml_config)
t0 = time.perf_counter()
g_fp = FoodParser(g_config)
print(f'加载模型时间:{(time.perf_counter() - t0) * 1000:.4f}ms')
app = Flask(__name__)


@app.route('/fea_extract', methods=['POST'])
def fea_extract():
    j_data = json.loads(request.data)
    imgData = base64.b64decode(j_data['image'])
    nparr = np.frombuffer(imgData, np.uint8)
    img_np = cv2.imdecode(nparr, cv2.IMREAD_COLOR)
    (row, col, chan) = img_np.shape
    t1 = time.perf_counter()
    feat = g_fp.get_feature(img_np.reshape((1, -1)), row, col, chan, 0)
    print(f'=====---coast:{(time.perf_counter() - t1) * 1000:.4f}ms')
    # feature = base64.b64encode(feat).decode('utf-8')
    feature = utils.feaSerializToStr(feat)
    result = {'feat': feature}
    return jsonify(result)


@app.route('/feas_extract', methods=['POST'])
def feas_extract():
    j_data = json.loads(request.data)
    bboxes = j_data['bboxes']
    # bboxes = [[743, 234, 1213, 740], [322, 193, 639, 505]]
    imgData = base64.b64decode(j_data['image'])
    nparr = np.frombuffer(imgData, np.uint8)
    img_np = cv2.imdecode(nparr, cv2.IMREAD_COLOR)
    (row, col, chan) = img_np.shape
    t1 = time.perf_counter()
    feats, boxes = g_fp.get_features(img_np.reshape((1, -1)), row, col, chan, 0, bboxes)
    print(f'=====---coast:{(time.perf_counter() - t1) * 1000:.4f}ms')
    print(feats.size, feats.shape)
    features = utils.feaSerializToStr(feats)
    result = {'feats': features, 'bboxex': bboxes}
    return jsonify(result)


if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5005, debug=False)
